package com.sojson.util.agent;

import com.alibaba.fastjson.JSONObject;
import com.sojson.constant.Constant;
import com.sojson.util.StringUtil;
import com.sojson.util.httpclient.HttpClientUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取地址类
 *
 * @author lyh
 */
@Slf4j
public class AddressUtil {

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    // 未知地址
    public static final String UNKNOWN = "XX XX";
    private static final Boolean isAddressEnabled = true;

    public static String getRealAddressByIP(String ip) {
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtil.internalIp(ip)) {
            return "内网IP";
        }
        if (isAddressEnabled) {
            try {
                String rspStr = doGet(IP_URL, "ip=" + ip + "&json=true", Constant.GBK);
                if (isBlank(rspStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSONObject.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return address;
    }

    /**
     * 判断一个字符串是否是空(空对象和空字符串)
     * 
     * @param obj
     * @return
     */
    private static boolean isBlank(String obj) {
        return StringUtil.isBlank(obj);
    }

    /**
     * 发送get请求
     * 
     * @param url 请求地址
     * @param headers 请求头(Json数据格式)
     * @param params 参数(Json数据格式)
     * @return
     * @throws Exception 
     */
    public static String doGet(String url, String headers, String params) throws Exception {
        return HttpClientUtil.doGet(url, headers, params);
    }

}